import React, { Component } from 'react';
import _ from 'underscore';
import moment from 'moment';

import Card from 'lib/components/card.jsx';
import Select from 'lib/components/Select.jsx';
import ChartWidget from 'lib/components/ChartWidget.jsx';

import { coreApi, parseToChart } from '../apis/core-util';

class Input extends Component {
  constructor(props, context) {
    super(props, context);

    this.state = {
      value: props.value
    };
  }

  changeHandler(e) {
    // console.log('e', e);
    // debugger
    let value = e.target.value.trim();

    if (value === '' || parseFloat(value).toString() !== value) {
      this.setState({ value });
    } else if (/[0-9]\d*/.test(value) || /[1-9]\d*.\d*|0.\d*[1-9]\d*/.test(value)) {
      if (value[value.length-1] === '.') {
        this.setState({ value });
      }
      else {
        this.props.onChange(e);
      }
    }
  } // changeHandler

  componentWillReceiveProps(nextProps) {
    this.setState({
      value: nextProps.value
    });
  } // componentWillReceiveProps

  render() {
    return (
      <input
        type={ this.props.type }
        id={ this.props.id }
        onChange={ this.changeHandler.bind(this) }
        value={ this.state.value }
        style={ this.props.style }
        className={ this.props.className } />
    );
  }
}

const parameters = [
  {
    unit: 'ms',
    label: '响应时间',
    calc: (value, y) => y.max > 200 ? value : value / 1000,
    requestParams: {
      urlName: 'httptransaction',
      viewKey: 'avg_resp',
      order: 2,
      classify: 'app',
      size: 30,
      offset: 0,
      limit: 1,
      classifyKeyField: 'time',
      classifyCountField: 'num',
      spanTime: moment.duration(1, 'days').valueOf(),
      endTime: null
    }
  },
  {
    unit: '%',
    label: '崩溃率',
    calc: value => value / 100,
    requestParams: {
      urlName: () => BlueWare.isIOS ? 'iosCrashRate' : 'androidCrashRate',
      viewKey: 'alert_crash_rate',
      order: 301,
      classify: 'app',
      size: 30,
      offset: 0,
      limit: 1,
      spanTime: moment.duration(1, 'days').valueOf(),
      endTime: null
    }
  },
  {
    unit: '%',
    label: 'HTTP错误率',
    calc: value => value / 100,
    requestParams: {
      urlName: 'errorrate',
      viewKey: 'error_rate',
      order: 2,
      classify: 'app',
      size: 30,
      offset: 0,
      limit: 1,
      statusCode: 400,
      spanTime: moment.duration(1, 'days').valueOf(),
      endTime: null
    }
  },
  {
    unit: '%',
    label: '网络错误率',
    calc: value => value / 100,
    requestParams: {
      urlName: 'errorrate',
      viewKey: 'error_rate',
      order: 2,
      classify: 'app',
      offset: 0,
      limit: 1,
      errorCode: 0,
      spanTime: moment.duration(1, 'days').valueOf(),
      endTime: null
    }
  }
];

export default class PolicyItem extends Component {
  constructor(props, context) {
    super(props, context);

    // this.updateLocalVariables(props);
    this.params = parameters[props.ruleType - 1];

    this.chartApi = coreApi(this.params.requestParams);

    this.uuid = `PolicyItem-preview-plot-line-${this.props.index}`;

    this.state = {
      chart: {
        loading: true
      },
      errorHTTPTransactionWarn: '',
      errorHTTPTransactionAlert: '',
      errorCrashRateWarn: '',
      errorCrashRateAlert: '',
      errorHTTPErrorWarn: '',
      errorHTTPErrorAlert: '',
      errorNetworkErrorWarn: '',
      errorNetworkErrorAlert: ''
    }; // state

    // 大于，小于，等于
    this.options = [
      {
        label: '大于',
        value: 'gt'
      }
      // ,{
      //   label: '小于',
      //   value: 'lt'
      // }
      // ,{
      //   label: '等于',
      //   value: 'equal'
      // }
    ];

    this.setPlotLine = this.setPlotLine.bind(this);
  }

  /**
   * Set plot line by value.
   *
   * @param {Nmuber} value
   */
  setPlotLine(value = this.props.criteria[1].threshold) {
    if (this.refs.preview.getChartObject() && this.refs.preview.getChartObject().chart) {
      let target = this.refs.preview.getChartObject().chart.yAxis[0];
      target.removePlotLine(this.uuid);
      target.addPlotLine({
        value: this.params.calc ? this.params.calc(value, target): value,
        color: 'red',
        width: 1,
        id: this.uuid
      });
    }
    // console.log(this.refs.preview.getChartObject());
  } // setPlotLine

  onCloseHandler() {
    this.props.onClose(this.props.index);
  } // onCloseHandler

  componentDidMount() {
    this.fetch();
  } // componentDidMount

  fetch() {
    this.chartApi
        .fetch()
        .progress(() => this.setState({
          chart: {
            loading: true
          }
        }))
        .fail(error => this.setState({
          chart: {
            error: error.responseText
          }
        }))
        .done((data, params) => this.setState({
          chart: {
            data: parseToChart(data, params)
          }
        }, () => this.setPlotLine()));
  }

  handlePropertyChange(key, {target, value}) {
    let special = ['groupBy', 'threshold', 'duration', 'cpm'];

    if (_.isUndefined(value)) {
      value = target.value;
    }

    if (_.indexOf(special, key) !== -1) {
      value = parseFloat(target.value);
      if (_.isNaN(value)) {
        value = 0;
      }
    }

    let { onPropertyChange } = this.props;

    if (_.isFunction(onPropertyChange)) {
      onPropertyChange(key, value);
    }
  } // handlePropertyChange

  handleCriteriaValueChange(index, key, {target}) {
    // console.log('target', target);
    let value = parseFloat(target.value),
        { onCriteriaValueChange } = this.props;

    if (_.isNaN(value)) {
      value = 0;
    }

    // console.log('this', this);
    // console.log('this.props', this.props);
    // console.log('this.props.options[0].criteria[0].thresholdMin', this.props.options[0].criteria[0].thresholdMin);
    // console.log('parameters', parameters);

    if (index === 1 && key === 'threshold') {
      this.setPlotLine(value);
    }

    // let isInvalid = undefined;
    if (this.props.ruleType === 1) {
      // debugger
      if (index === 0) {
        if (value < this.props.options[0].criteria[0].thresholdMin) {
          this.setState({
            errorHTTPTransactionWarn: '(最小值:'+this.props.options[0].criteria[0].thresholdMin+')'
          });
          // isInvalid = true;
        }
        else {
          this.setState({
            errorHTTPTransactionWarn: ''
          });
        }
      }

      if (index === 1) {
        if (value < this.props.options[0].criteria[1].thresholdMin) {
          this.setState({
            errorHTTPTransactionAlert: '(最小值:'+this.props.options[0].criteria[1].thresholdMin+')'
          });
          // isInvalid = true;
        }
        else {
          this.setState({
            errorHTTPTransactionAlert: ''
          });
        }
      }
    }
    if (this.props.ruleType === 2) {
      if (index === 0) {
        if (value < this.props.options[1].criteria[0].thresholdMin) {
          this.setState({
            errorCrashRateWarn: '(最小值:'+this.props.options[1].criteria[0].thresholdMin+')'
          });
        }
        else {
          this.setState({
            errorCrashRateWarn: ''
          });
        }
      }

      if (index === 1) {
        if (value < this.props.options[1].criteria[1].thresholdMin) {
          this.setState({
            errorCrashRateAlert: '(最小值:'+this.props.options[1].criteria[1].thresholdMin+')'
          });
        }
        else {
          this.setState({
            errorCrashRateAlert: ''
          });
        }
      }
    }
    if (this.props.ruleType === 3) {
      if (index === 0) {
        if (value < this.props.options[2].criteria[0].thresholdMin) {
          this.setState({
            errorHTTPErrorWarn: '(最小值:'+this.props.options[2].criteria[0].thresholdMin+')'
          });
        }
        else {
          this.setState({
            errorHTTPErrorWarn: ''
          });
        }
      }

      if (index === 1) {
        if (value < this.props.options[2].criteria[1].thresholdMin) {
          this.setState({
            errorHTTPErrorAlert: '(最小值:'+this.props.options[2].criteria[1].thresholdMin+')'
          });
        }
        else {
          this.setState({
            errorHTTPErrorAlert: ''
          });
        }
      }
    }
    if (this.props.ruleType === 4) {
      if (index === 0) {
        if (value < this.props.options[3].criteria[0].thresholdMin) {
        this.setState({
          errorNetworkErrorWarn: '(最小值:'+this.props.options[3].criteria[0].thresholdMin+')'
        });
      }
      else {
        this.setState({
          errorNetworkErrorWarn: ''
        });
      }
    }

      if (index === 1) {
        if (value < this.props.options[3].criteria[1].thresholdMin) {
          this.setState({
            errorNetworkErrorAlert: '(最小值:'+this.props.options[3].criteria[1].thresholdMin+')'
          });
        }
        else {
          this.setState({
            errorNetworkErrorAlert: ''
          });
        }
      }
    }
    // console.log(index, key, value);

    if (_.isFunction(onCriteriaValueChange)) {
      onCriteriaValueChange(index, key, value);
      // onCriteriaValueChange(index, key, value, isInvalid);
    }
  } // handleCriteriaValueChange

  render() {
    let options = [],
        { ruleType } = this.props;

    _.forEach(this.props.options, (option) => {
      if (option.ruleType === ruleType || option.createable) {
        options.push( option );
      }
    });

    return (
      <div className="pure-g mp-box">
        <div className="pure-u-7-12">
          <Card className="items r4" extra={
            this.props.remove
              ? (
                <a
                  className="iconfont"
                  href="javascript:;"
                  onClick={ this.onCloseHandler.bind(this) }>
                  &#xe63d;
                </a>
              ) : null
          }>
            <div className="type-container">
              <Select
                className="type-condition"
                options={ options }
                onChange={ this.handlePropertyChange.bind(this, 'ruleType') }
                value={ this.props.ruleType + '' } />
            </div>
            <ul className="condition-container">
              <li className="auto-row">
                <label className="left" htmlFor={ 'trigger-condition-' + this.props.index }>触发条件：</label>
                <div className="main">
                  <span>吞吐量 >=</span>
                  <input id={ 'trigger-condition-' + this.props.index } type="text" className="input-text input-text-80"
                    onChange={ this.handlePropertyChange.bind(this, 'cpm') } value={ this.props.cpm } />
                  <span className="mr6">cpm</span>
                  {/*<input id={ 'trigger-condition-check-' + this.props.index } type="checkbox"
                    onChange={ this.handlePropertyChange.bind(this, 'criteriaType') } />
                  <label htmlFor={ 'trigger-condition-check-' + this.props.index }>例外</label>*/}
                </div>
              </li>
              {
                this.props.criteria.map((criteria, index) => {
                  return (
                    <li className="auto-row" key={ index }>
                      <label className="left" htmlFor={ 'threshold-warn-' + this.props.index }>{ index === 0 ? '告警阈值' : '严重阈值' }：</label>
                      <div className="main">
                        <span>持续</span>
                        <input id={ 'threshold-warn-' + this.props.index + index } className="input-text input-value mlr6"
                          onChange={ this.handleCriteriaValueChange.bind(this, index, 'duration') } type="text" value={ criteria.duration } />
                        <span>分钟</span>
                        <span className="infill"></span>
                        <Input
                          id={ 'threshold-warn-' + this.props.index + index }
                          className="input-text input-value mlr6"
                          onChange={ this.handleCriteriaValueChange.bind(this, index, 'threshold') }
                          type="text"
                          value={ criteria.threshold } />
                        <span>{ this.params.unit }</span>
                        <span className="msg-error" style={{ marginLeft: '4px', color: '#eac85e', clear: 'both', fontSize: '12px', display: 'inline-block' }}>
                          { (this.props.ruleType === 1 && index === 0) ? this.state.errorHTTPTransactionWarn : null }
                          { (this.props.ruleType === 1 && index === 1) ? this.state.errorHTTPTransactionAlert : null }
                          { (this.props.ruleType === 2 && index === 0) ? this.state.errorCrashRateWarn : null }
                          { (this.props.ruleType === 2 && index === 1) ? this.state.errorCrashRateAlert : null }
                          { (this.props.ruleType === 3 && index === 0) ? this.state.errorHTTPErrorWarn : null }
                          { (this.props.ruleType === 3 && index === 1) ? this.state.errorHTTPErrorAlert : null }
                          { (this.props.ruleType === 4 && index === 0) ? this.state.errorNetworkErrorWarn : null }
                          { (this.props.ruleType === 4 && index === 1) ? this.state.errorNetworkErrorAlert : null }
                        </span>
                      </div>
                    </li>
                  );
                })
              }
              <li className="auto-row">
                <label className="left">分组方式：</label>
                <div className="main">
                  <div className="pure-g" style={{ width: '320px' }}>
                    <div className="pure-u-1-3">
                      <label>
                        <input
                        type="radio"
                        className="mr6"
                        name={ `type-of-group-${this.props.index}` }
                        defaultChecked={ this.props.groupBy === 1 }
                        value="1" onChange={ this.handlePropertyChange.bind(this, 'groupBy') } />
                        总体
                      </label>
                    </div>
                    { (this.props.ruleType === 2) ? null:
                      (<div className="pure-u-1-3">
                        <label>
                          <input
                          type="radio"
                          className="mr6"
                          defaultChecked={ this.props.groupBy === 2 }
                          name={ `type-of-group-${this.props.index}` }
                          value="2" onChange={ this.handlePropertyChange.bind(this, 'groupBy') } />
                          区域
                        </label>
                      </div>)}
                    { (this.props.ruleType === 2) ? null:
                      (<div className="pure-u-1-3">
                        <label>
                          <input
                          type="radio"
                          className="mr6"
                          defaultChecked={ this.props.groupBy === 3 }
                          name={ `type-of-group-${this.props.index}` }
                          value="3" onChange={ this.handlePropertyChange.bind(this, 'groupBy') } />
                          区域和运营商
                        </label>
                      </div>)}
                  </div>
                </div>
              </li>
            </ul>
            <div className="selector-operator">
              <Select options={ this.options } value={ _.last(this.props.criteria).operation } onChange={ this.handlePropertyChange.bind(this, 'operation') } />
            </div>
          </Card>
        </div>
        <div className="pure-u-5-12">
          <Card className="widget-float r4">
            <div>预览</div>
            <div style={{ padding: '7.5px' }}>
              <ChartWidget ref="preview" height={ 188 } store={ this.state.chart } chartSettings={{
                chart: {
                  animation: false
                },
                tooltip: {
                  enabled: false
                },
                legend: {
                  enabled: false
                },
                xAxis: {
                  labels: {
                    enabled: false
                  }
                },
                yAxis: {
                  labels: {
                    y: -3
                  },
                  offset: -5
                }
              }} />
            </div>
          </Card>
        </div>
      </div>
    )
  }
}

PolicyItem.defaultProps = {
  index: 0,
  item: null,
  onTypeChanged: value => {},
  onClose: index => {},
  options: [],
  onPropertyChange: null,
  onCriteriaValueChange: null
}
